package club.janna.hello.server;


import club.janna.hello.parser.constants.IEC104Statute;
import club.janna.hello.util.DataConvertor;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;


/**
 * Created by guopanbo on 17/11/27.
 */
public class ServerHandle extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        System.out.println("建立连接：" + ctx.channel().remoteAddress());
        //发送起始帧
        sendData(ctx, IEC104Statute.starting(0, 0));
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        System.out.println("断开连接：" + ctx.channel().remoteAddress());
    }

    /**
     * 发送数据
     * @param data
     */
    private void sendData(ChannelHandlerContext ctx, byte[] data) {
        if(ctx != null && ctx.channel() != null && ctx.channel().isActive()) {
            //byte[] data = new byte[]{0x68, 0x04, 0x01, 0x00, 0x02, 0x00};
            //byte[] data = "hello ".getBytes();
            //byte[] data = IEC104Statute.TEST_ACK_DATA;
            ctx.writeAndFlush(Unpooled.copiedBuffer(data));
            System.out.println("发送数据：" + DataConvertor.Byte2String(data));
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //super.channelRead(ctx, msg);
        //System.out.println(11);
        //接收的数据
        ByteBuf buf = (ByteBuf) msg;
        byte[] data = new byte[buf.readableBytes()];
        buf.readBytes(data);
        //解析数据
        ParseHandle.parse(data, ctx);
        //int[] intData = DataConvertor.HexByteArray2DecArray(data);
        //for(int b : intData)
        //    System.out.print(b + " ");
        //System.out.println();
        //返回的数据
        //ctx.writeAndFlush(Unpooled.copiedBuffer("68 04 11 01 02 03 04".getBytes()));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        cause.printStackTrace();
    }
}
